package com.quanyan.club.thread;

import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.db.TbClubMember;
import com.quanyan.search.entity.vo.ClubMemberIndexInfo;
import com.quanyan.search.service.ClubMemberSearchService;
import org.apache.commons.lang.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Created by zhuo.shi on 2016/10/20.
 */
public class ClubMemberSolrIndexThread implements Runnable {

    private Logger logger = LoggerFactory.getLogger(ClubMemberSolrIndexThread.class);

    private int op;
    private TbClubMember clubMember;
    private String nickName;
    private ClubMemberSearchService clubMemberSearchService;

    public ClubMemberSolrIndexThread(TbClubMember clubMember, String nickName,
                                     ClubMemberSearchService clubMemberSearchService,
                                     int op){
        this.op = op;       // 1 添加 2 删除 3 更新
        this.clubMember = clubMember;
        this.nickName = nickName;
        this.clubMemberSearchService = clubMemberSearchService;
    }

    @Override
    public void run() {
        if (clubMember == null) {
            return;
        }
        int uid = clubMember.getUid();
        int clubId = clubMember.getClubId();

        ClubMemberIndexInfo indexInfo = new ClubMemberIndexInfo();
        indexInfo.setClub_member_uid(String.valueOf(clubMember.getUid()));
        indexInfo.setClub_id_mem(String.valueOf(clubMember.getClubId()));
        indexInfo.setClub_member_nickname(nickName);
        indexInfo.setClub_role_name(clubMember.getRoleName());
        indexInfo.setClub_team_label_name(clubMember.getTeamLabelName());
        logger.warn("--------clubMember Index=" + JSON.toJSONString(indexInfo) + ", op=" + op);
        if (op == 1){
            StopWatch sw = new StopWatch();
            sw.start();
            //添加俱乐部成员信息索引到slor cloud
            APIResponse response = clubMemberSearchService.insertDoc(indexInfo);
            if (response == null || !response.isRet()){
                logger.info("添加俱乐部成员索引失败：{}", JSON.toJSON(response));
            }
            sw.stop();
            logger.warn("添加俱乐部成员索引clubId={}, uid={}, 花费：{}", clubId  ,uid, sw.getTime());
        }else if (op == 2){
            StopWatch sw = new StopWatch();
            sw.start();
            clubMemberSearchService.deleteDocById(clubId, uid);
            sw.stop();
            logger.warn("删除俱乐部成员索引clubId={}, uid={}, 花费：{}", clubId  ,uid, sw.getTime());
        }else if (op == 3){
            StopWatch sw = new StopWatch();
            sw.start();
            APIResponse response = clubMemberSearchService.deleteDocById(clubId, uid);
            if (response.isRet()) {
                clubMemberSearchService.insertDoc(indexInfo);
            }
            sw.stop();
            logger.warn("更新俱乐部成员索引clubId={}, uid={}, 花费：{}", clubId  ,uid, sw.getTime());
        }
    }
}
